package com.AO.struts;

import java.io.UnsupportedEncodingException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import com.AO.DAO.*;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Query;

public class Search {
	private String keyword;
	private String type;
	public String getKeyword() {
		return keyword;
	}
	public void setKeyword(String keyword) throws UnsupportedEncodingException {
		this.keyword = new String(keyword.getBytes("ISO-8859-1"),"utf8");
	}
	
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String execute()throws Exception
	{
		
		if(type.equals("user"))
		{
		HttpServletRequest request=ServletActionContext.getRequest();
		UserDAO dao=new UserDAO();
		Set<User>set=new HashSet<User>();
		Query q=dao.getSession().createSQLQuery("select nick_name from User where nick_name like '%"+keyword+"%'");  
        List<String>li=(List<String>)q.list();
        for(String keyword:li)
        {
	    set.addAll(dao.findByNickName(keyword));
        }
	    request.setAttribute("cookerList",set);
	    return "CookerList";
		}
		if(type.equals("fmf"))
		{
			HttpServletRequest request=ServletActionContext.getRequest();
			
			FoodDAO dao=new FoodDAO();
			MaterialFoodDAO dao2=new MaterialFoodDAO();
			
			Set<Food>set=new HashSet<Food>();
			Set<MaterialFood>set2=new HashSet<MaterialFood>();
						
			Query q=dao.getSession().createSQLQuery("select food_id from food where food_name like '%"+keyword+"%'");  
	        List<String>li=(List<String>)q.list();
	        for(String keyword:li)
	        {
		    set.add(dao.findById(keyword));
	        }
	        
	        q=dao.getSession().createSQLQuery("select material_food_id from material_food where material_food_name like '%"+keyword+"%'");  
	        li=(List<String>)q.list();
	        for(String keyword:li)
	        {
		    set2.add(dao2.findById(keyword));
	        }
	        
	        request.setAttribute("foodList", set);
	        request.setAttribute("mfoodList", set2);
			return "SearchPage";
		}
		else
		{
			return"wrongPage";
		}
	}
}
